﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frame.DataHelper;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Runtime.Serialization;
using DevExpress.Web.ASPxGridView.Export;
using System.IO;
using System.Web.UI;
using System.Reflection;
using System.Data;
using System.Data.Linq;
using System.Web.UI.WebControls;
using System.Drawing;
using DevExpress.Utils;

namespace Frame.Global
{
    #region 枚举类型
    /// <summary>
    /// 操作类型，用于日志记录
    /// </summary>
    public enum ActionType
    {
        /// <summary>
        /// 登入操作
        /// </summary>
        Login,
        /// <summary>
        /// 登出操作
        /// </summary>
        Logout,
        /// <summary>
        /// 删除操作
        /// </summary>
        Delete,
        /// <summary>
        /// 更新操作
        /// </summary>
        Update,
        /// <summary>
        /// 插入操作
        /// </summary>
        Insert,
        /// <summary>
        /// 批量生成操作
        /// </summary>
        Gen
    }
    /// <summary>
    /// 用户类型
    /// </summary>
    public enum UserType
    {
        /// <summary>
        /// 客户
        /// </summary>
        Customers,
        /// <summary>
        /// 内部用户
        /// </summary>
        InnerUsers
    }
    /// <summary>
    /// 导出格式
    /// </summary>
    public enum ExportType
    {
        Excel,
        Rtf,
        Pdf
    }
    #endregion
    ///<summary>
    ///版权所有：css
    ///内容摘要：公共方法类，包含所有的公共静态方法。已抽象。
    ///完成日期：2008年7月
    ///版本：V 1.0
    ///作者：陈慧君
    ///
    ///修改记录1：
    ///修改日期：2012/3/29
    ///版本号：V 1.1
    ///修改人：苏俊轩
    ///修改内容：
    ///</summary>
    public abstract class GlobalFunctions
    {
        #region 苏俊轩新增方法
        /// <summary>
        /// 补齐编码
        /// </summary>
        /// <param name="code">原编码</param>
        /// <param name="letter">头字母</param>
        /// <param name="length">补齐长度</param>
        /// <returns></returns>
        public static string GenerateCode(string code, char letter, int length)
        {
            for (int i = code.Length; i < length - 1; i++)
            {
                code = "0" + code;
            }
            code = letter + code;
            return code;
        }

        /// <summary>
        /// 生成拼音简码    
        /// <param name="unicodeString">Unicode编码字符串</param>
        /// <returns>拼音简码:string</returns>
        /// </summary>
        public static string GetPinyinCode(string unicodeString)
        {
            int i = 0;
            ushort key = 0;
            string strResult = string.Empty;

            //创建两个不同的encoding对象
            Encoding unicode = Encoding.Unicode;
            //创建GBK码对象
            Encoding gbk = Encoding.GetEncoding(936);
            //将unicode字符串转换为字节
            byte[] unicodeBytes = unicode.GetBytes(unicodeString);
            //再转化为GBK码
            byte[] gbkBytes = Encoding.Convert(unicode, gbk, unicodeBytes);
            while (i < gbkBytes.Length)
            {
                //如果为数字\字母\其他ASCII符号
                if (gbkBytes[i] <= 127)
                {
                    strResult = strResult + (char)gbkBytes[i];
                    i++;
                }
                #region 否则生成汉字拼音简码,取拼音首字母
                else
                {

                    key = (ushort)(gbkBytes[i] * 256 + gbkBytes[i + 1]);
                    if (key >= '\uB0A1' && key <= '\uB0C4')
                    {
                        strResult = strResult + "A";
                    }
                    else if (key >= '\uB0C5' && key <= '\uB2C0')
                    {
                        strResult = strResult + "B";
                    }
                    else if (key >= '\uB2C1' && key <= '\uB4ED')
                    {
                        strResult = strResult + "C";
                    }
                    else if (key >= '\uB4EE' && key <= '\uB6E9')
                    {
                        strResult = strResult + "D";
                    }
                    else if (key >= '\uB6EA' && key <= '\uB7A1')
                    {
                        strResult = strResult + "E";
                    }
                    else if (key >= '\uB7A2' && key <= '\uB8C0')
                    {
                        strResult = strResult + "F";
                    }
                    else if (key >= '\uB8C1' && key <= '\uB9FD')
                    {
                        strResult = strResult + "G";
                    }
                    else if (key >= '\uB9FE' && key <= '\uBBF6')
                    {
                        strResult = strResult + "H";
                    }
                    else if (key >= '\uBBF7' && key <= '\uBFA5')
                    {
                        strResult = strResult + "J";
                    }
                    else if (key >= '\uBFA6' && key <= '\uC0AB')
                    {
                        strResult = strResult + "K";
                    }
                    else if (key >= '\uC0AC' && key <= '\uC2E7')
                    {
                        strResult = strResult + "L";
                    }
                    else if (key >= '\uC2E8' && key <= '\uC4C2')
                    {
                        strResult = strResult + "M";
                    }
                    else if (key >= '\uC4C3' && key <= '\uC5B5')
                    {
                        strResult = strResult + "N";
                    }
                    else if (key >= '\uC5B6' && key <= '\uC5BD')
                    {
                        strResult = strResult + "O";
                    }
                    else if (key >= '\uC5BE' && key <= '\uC6D9')
                    {
                        strResult = strResult + "P";
                    }
                    else if (key >= '\uC6DA' && key <= '\uC8BA')
                    {
                        strResult = strResult + "Q";
                    }
                    else if (key >= '\uC8BB' && key <= '\uC8F5')
                    {
                        strResult = strResult + "R";
                    }
                    else if (key >= '\uC8F6' && key <= '\uCBF9')
                    {
                        strResult = strResult + "S";
                    }
                    else if (key >= '\uCBFA' && key <= '\uCDD9')
                    {
                        strResult = strResult + "T";
                    }
                    else if (key >= '\uCDDA' && key <= '\uCEF3')
                    {
                        strResult = strResult + "W";
                    }
                    else if (key >= '\uCEF4' && key <= '\uD188')
                    {
                        strResult = strResult + "X";
                    }
                    else if (key >= '\uD1B9' && key <= '\uD4D0')
                    {
                        strResult = strResult + "Y";
                    }
                    else if (key >= '\uD4D1' && key <= '\uD7F9')
                    {
                        strResult = strResult + "Z";
                    }
                    else
                    {
                        strResult = strResult + "?";
                    }
                    i = i + 2;
                }
                #endregion
            }//end while

            return strResult;
        }

        #endregion

        /// <summary>
        /// sql语句参数整理方法
        /// </summary>
        /// <param name="PramsString">需要整理的sql参数</param>
        /// <returns>返回整理好的sql参数</returns>
        public static string SqlPramsTrim(string PramsString)
        {
            //目前暂定只去除空格和单引号
            string returnstr = PramsString.Trim().Replace("'", "''");
            return returnstr;
        }
        /// <summary>
        /// 获取sysinfo的相应的sysxm的值
        /// </summary>
        /// <param name="sysxm">xm值</param>
        /// <returns></returns>
        public static string GetSysinfo(string sysxm)
        {
            string sqlstr = "select sm from sm_sysinfo where xm='" + SqlPramsTrim(sysxm) + "'";
            try
            {
                return GlobalSqlHelper.ExcuteSQLScalar(sqlstr).ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 判断字符串是否是数字
        /// </summary>
        /// <param name="strNumber">需要进行判断的字符串</param>
        /// <returns></returns>
        public static bool IsNumber(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");

            return !objNotNumberPattern.IsMatch(strNumber) &&
            !objTwoDotPattern.IsMatch(strNumber) &&
            !objTwoMinusPattern.IsMatch(strNumber) &&
            objNumberPattern.IsMatch(strNumber);
        }


        public static string f_GetToken(ref string pStr, string pStrToken)
        {
            //根据pStrToken分割pStr
            int i = pStr.IndexOf(pStrToken);
            int j = pStrToken.Length;
            int k = pStr.Length;
            if (i > 0)
            {
                string pNewStr = pStr.Substring(0, i);
                pStr = pStr.Substring(i + j, k - i - j);
                return pNewStr;
            }
            else
            {
                string pNewStr = pStr.ToString();
                pStr = "";
                return pNewStr;
            }
        }


        public static string f_GetToken(string pStr, string pStrToken, ref string pStrRet)
        {
            //根据pStrToken分割pStr
            int i = pStr.IndexOf(pStrToken);
            int j = pStrToken.Length;
            int k = pStr.Length;
            if (i > 0)
            {
                pStrRet = pStr.Substring(i + j, k - i - j);
                return pStr.Substring(0, i);
            }
            else
            {
                pStrRet = "";
                return pStr;
            }
        }


        /// <summary>
        /// 进行DES加密。
        /// </summary>
        /// <param name="sToDES">要加密的字符串。</param>
        /// <returns>以Base64格式返回的加密字符串。</returns>
        public static string EnCodeDES(string sToDES)
        {
            string sKey = "ILoveCc!";
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(sToDES);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        public static string EnCodeDES(string pKey, string sToDES)
        {
            string sKey = pKey;
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(sToDES);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }


        /// <summary>
        /// 进行DES解密。
        /// </summary>
        /// <param name="sToDES">要解密的字符串。</param>
        /// <returns>以Base64格式返回的解密字符串。</returns>
        public static string DeCodeDES(string sOfDES)
        {
            string sKey = "ILoveCc!";
            byte[] inputByteArray = Convert.FromBase64String(sOfDES);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }


        public static string DeCodeDES(string pKey, string sOfDES)
        {
            string sKey = pKey;
            byte[] inputByteArray = Convert.FromBase64String(sOfDES);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }



        /// <summary>
        /// 进行MD5 32位加密。
        /// </summary>
        /// <param name="sToMd5">要加密或解密的字符串。</param>
        /// <returns>加密字符串。</returns>
        public static string MD5(string sToMd5)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sToMd5, "MD5").ToLower();
        }


        /// <summary>
        /// 在一个SQL语句中插入一段条件语句
        /// </summary>
        /// <param name="sSqlString">被插入的SQL。</param>
        /// <param name="sCondition">插入条件</param>
        /// <returns>新的字符串。</returns>
        public static string InsertSqlCondition(string sSqlString, string sCondition)
        {
            string ls_sql, ls_sort, ls_group, ls_having, ls_oldwhere;
            if (sCondition == "")
            {
                return sSqlString;
            }
            ls_sql = sSqlString.ToLower();
            ls_sort = ls_sql;
            ls_sql = GlobalFunctions.f_GetToken(ref ls_sort, "order by"); /*get the sort clouse*/
            ls_group = ls_sql;
            ls_sql = GlobalFunctions.f_GetToken(ref ls_group, "group by");  /*get the group clouse*/
            ls_having = ls_sql;
            ls_sql = GlobalFunctions.f_GetToken(ref ls_having, "having");  /*get the having clouse*/
            ls_oldwhere = ls_sql;
            ls_sql = GlobalFunctions.f_GetToken(ref ls_oldwhere, "where");  /*get the select clouse*/
            if (ls_oldwhere != "")
            {
                ls_sql = ls_sql + " where (" + sCondition + ") and (" + ls_oldwhere + ")";
            }
            else
            {
                ls_sql = ls_sql + " where (" + sCondition + ")";
            }
            if (ls_group != "")
            {
                ls_sql = ls_sql + " group by " + ls_group;
            }
            if (ls_having != "")
            {
                ls_sql = ls_sql + " having " + ls_having;
            }
            if (ls_sort != "")
            {
                ls_sql = ls_sql + " order by " + ls_sort;
            }
            return ls_sql;
        }
        /// <summary>
        /// 判断传进来的字符串是否是PLU码
        /// </summary>
        /// <param name="sPlu">需要判断字符串</param>
        /// <returns>返回是或否PLU</returns>
        public static bool IsPlu(string sPlu)
        {
            int iPlu = sPlu.Length;
            if (iPlu == 8 || iPlu == 13)
            {
                string tmp1 = sPlu.Substring(0, iPlu - 1);
                string tmp2 = sPlu.Substring(iPlu - 1, 1);
                if (gen_paritybit(tmp1) == tmp2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 计算PLU的校验位
        /// </summary>
        /// <param name="as_string">PLU的前7或12位字符串</param>
        /// <returns>校验位</returns>
        public static string gen_paritybit(string as_string)
        {
            /*根据传递过来的字符串产生校检位*/
            string ls_char, ls_ret;
            int ll_i, ll_total = 0, ll_len;

            /*条码检验规则:(检验位与其每相隔位的和)+3*(剩余位的和)=10的倍数*/
            ll_len = as_string.Length;
            for (ll_i = ll_len - 1; ll_i >= 0; ll_i -= 2)/*计算检验位前一位与其每相隔位的和*/
            {
                ls_char = as_string.Substring(ll_i, 1);
                ll_total = ll_total + Convert.ToInt32(ls_char);
            }
            ll_total = ll_total * 3;  /*乘3*/
            for (ll_i = ll_len - 2; ll_i >= 0; ll_i -= 2)  /*加上剩余位的和*/
            {
                ls_char = as_string.Substring(ll_i, 1);
                ll_total = ll_total + Convert.ToInt32(ls_char);
            }
            string ls_Str = Convert.ToString((10 - (ll_total % 10)));
            ls_ret = ls_Str.Substring(ls_Str.Length - 1, 1);
            return ls_ret;
        }

        /// <summary>
        /// 按sqlstr获取下拉框的item
        /// </summary>
        /// <param name="Column">下拉框列</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        public static void InitComboBoxColumn(GridViewColumn Column, string TableName, string TextField, string ValueField)
        {
            GridViewDataComboBoxColumn gvdcb = Column as GridViewDataComboBoxColumn;
            DataTable dt = new DataTable();
            dt = GlobalSqlHelper.ExecuteSQLToDataTable(string.Format("select {0},{1} from {2}", TextField, ValueField, TableName));
            foreach (DataRow dr in dt.Rows)
            {
                gvdcb.PropertiesComboBox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(dr[TextField].ToString(), dr[ValueField].ToString()));
            }
        }
        /// <summary>
        /// 直接通过字符数组获取下拉框的item
        /// </summary>
        /// <param name="Column">下拉框列列名</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        public static void InitComboBoxColumn(GridViewColumn Column, string[] TextArray, string[] ValueArray)
        {
            GridViewDataComboBoxColumn gvdcb = Column as GridViewDataComboBoxColumn;
            for (int i = 0; i < TextArray.Length; i++)
            {
                gvdcb.PropertiesComboBox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(TextArray[i], ValueArray[i]));
            }
        }


        /// <summary>
        /// 直接通过字符数组获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        public static void InitComboBox(ASPxComboBox combobox, string[] TextArray, string[] ValueArray)
        {
            for (int i = 0; i < TextArray.Length; i++)
            {
                combobox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(TextArray[i], ValueArray[i]));
            }
        }
        /// <summary>
        /// 按sqlstr获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        public static void InitComboBox(ASPxComboBox combobox, string TableName, string TextField, string ValueField)
        {
            DataTable dt = new DataTable();
            dt = GlobalSqlHelper.ExecuteSQLToDataTable(string.Format("select {0},{1} from {2}", TextField, ValueField, TableName));
            foreach (DataRow dr in dt.Rows)
            {
                combobox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(dr[TextField].ToString(), dr[ValueField].ToString()));
            }
        }


        /// <summary>
        /// 弹出alert消息，跳转到指定URL
        /// </summary>
        /// <param name="Msg">消息</param>
        /// <param name="url">url</param>
        public static void AlertToUrl(string Msg, string url)
        {
            #region
            Msg = "alert(\"" + Msg + "\");location.href=\"" + url + "\";";
            System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
            page.ClientScript.RegisterStartupScript(typeof(string), "", Msg, true);
            #endregion
        }
        /// <summary>
        /// 弹出alert消息
        /// </summary>
        /// <param name="msg">消息</param>
        public static void Alert(string Msg)
        {
            #region
            Msg = "alert(\"" + Msg + "\");";
            System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
            page.ClientScript.RegisterStartupScript(typeof(string), "", Msg, true);
            #endregion
        }

        /// <summary>
        /// 设置GridView的一般格式
        /// </summary>
        /// <param name="TheGridView"></param>
        /// <param name="IsAddCommandCol">是否添加命令列</param>
        public static void SetGridView(ASPxGridView TheGridView, bool IsAddCommandCol)
        {
            TheGridView.SettingsText.CommandCancel = "取消";
            TheGridView.SettingsText.CommandClearFilter = "清除筛选条件";
            TheGridView.SettingsText.CommandDelete = "删除";
            TheGridView.SettingsText.CommandEdit = "编辑";
            TheGridView.SettingsText.CommandNew = "新增";
            TheGridView.SettingsText.CommandSelect = "选择";
            TheGridView.SettingsText.CommandUpdate = "更新";
            TheGridView.SettingsText.ConfirmDelete = "确实要进行删除？";
            TheGridView.SettingsText.EmptyDataRow = "没有可显示的数据";
            TheGridView.SettingsText.EmptyHeaders = "";
            TheGridView.SettingsText.PopupEditFormCaption = "编辑";  //(by SU)
            TheGridView.SettingsLoadingPanel.Text = "读取中...";
            TheGridView.SettingsPager.Summary.Text = "当前第{0}页，共{1}页，{2}条记录";

            TheGridView.SettingsText.FilterBarCreateFilter = "高级查询"; //(by SU)
            //TheGridView.SettingsText.FilterBarClear = "清除查询条件";  //(by SU)
            TheGridView.SettingsText.FilterControlPopupCaption = "查询条件"; //(by SU)
            TheGridView.SettingsBehavior.AllowDragDrop = false;
            TheGridView.Font.Size = FontUnit.Parse("10pt");
            // TheGridView.SettingsPager.SEOFriendly = DevExpress.Web.ASPxPager.SEOFriendlyMode.Enabled;
            TheGridView.SettingsPager.PageSize = 20;
            TheGridView.SettingsBehavior.ConfirmDelete = true;

            //数据行交替显示
            TheGridView.Styles.AlternatingRow.Enabled = DefaultBoolean.True;

            if (IsAddCommandCol)
            {
                //防止重复添加
                if (null != TheGridView.Columns["inputcmdcol"])
                {
                }
                else
                {
                    //增加一个清理列
                    GridViewCommandColumn commandColumn = new GridViewCommandColumn();

                    commandColumn.Name = "inputcmdcol";
                    commandColumn.ClearFilterButton.Visible = true;
                    commandColumn.ClearFilterButton.Text = "清除过滤信息";
                    commandColumn.ShowSelectCheckbox = false; ;
                    commandColumn.EditButton.Visible = true;
                    commandColumn.EditButton.Text = "编辑";

                    commandColumn.DeleteButton.Visible = true;
                    commandColumn.DeleteButton.Text = "删除";
                    commandColumn.NewButton.Visible = true;
                    commandColumn.NewButton.Text = "新增";
                    commandColumn.UpdateButton.Visible = true;
                    commandColumn.UpdateButton.Text = "更新";
                    commandColumn.CancelButton.Visible = true;
                    commandColumn.CancelButton.Text = "取消";
                    commandColumn.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                    commandColumn.Caption = "操作";
                    TheGridView.Columns.Add(commandColumn);
                }
            }
            foreach (GridViewColumn item in TheGridView.Columns)//通过foreach例遍所有的Columns
            {
                item.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;

                if (item is GridViewDataComboBoxColumn)//当响应的columns为下拉框时设置文字显示为居中
                {
                    item.CellStyle.HorizontalAlign = HorizontalAlign.Center;
                }

                if (item is GridViewDataTextColumn)
                {
                    //验证不通过时自动聚焦(by SU)
                    (item as GridViewDataTextColumn).PropertiesTextEdit.ValidationSettings.SetFocusOnError = true;
                }
            }
        }

        /// <summary>
        /// 根据用户权限设置GridView（增删改查）基本功能(by SU)
        /// </summary>
        /// <param name="TheGridView"></param>
        /// <param name="Functions">功能代码</param>
        public static void SetFunctions(ASPxGridView TheGridView, string Functions)
        {
            if (!String.IsNullOrEmpty(Functions))
            {
                //防止重复添加
                if (null != TheGridView.Columns["inputcmdcol"])
                {
                }
                else
                {
                    //增加一个命令列
                    GridViewCommandColumn commandColumn = new GridViewCommandColumn();

                    commandColumn.Name = "inputcmdcol";
                    commandColumn.ShowSelectCheckbox = false; ;

                    commandColumn.ClearFilterButton.Visible = true;
                    commandColumn.ClearFilterButton.Text = "清除过滤信息";

                    if (!String.IsNullOrEmpty(GlobalRunParms.ClearIcon))
                    {
                        commandColumn.ClearFilterButton.Image.Url = GlobalRunParms.ClearIcon;
                        commandColumn.EditButton.Image.ToolTip = "清除过滤信息";
                    }

                    //拥有更新权限
                    if (Functions.Contains("U"))
                    {
                        commandColumn.EditButton.Visible = true;
                        commandColumn.EditButton.Text = "编辑";

                        if (!String.IsNullOrEmpty(GlobalRunParms.EditIcon))
                        {
                            commandColumn.EditButton.Image.Url = GlobalRunParms.EditIcon;
                            commandColumn.EditButton.Image.ToolTip = "编辑";
                        }
                    }
                    //拥有删除权限
                    if (Functions.Contains("D") && "Y".Equals(GlobalRunParms.GlobalDelete))
                    {
                        commandColumn.DeleteButton.Visible = true;
                        commandColumn.DeleteButton.Text = "删除";

                        if (!String.IsNullOrEmpty(GlobalRunParms.DeleteIcon))
                        {
                            commandColumn.DeleteButton.Image.Url = GlobalRunParms.DeleteIcon;
                            commandColumn.DeleteButton.Image.ToolTip = "删除";
                        }
                    }
                    //拥有新增权限
                    if (Functions.Contains("I"))
                    {
                        commandColumn.NewButton.Visible = true;
                        commandColumn.NewButton.Text = "新增";

                        if (!String.IsNullOrEmpty(GlobalRunParms.AddIcon))
                        {
                            commandColumn.NewButton.Image.Url = GlobalRunParms.AddIcon;
                            commandColumn.NewButton.Image.ToolTip = "新增";
                        }
                    }
                    //拥有查看权限
                    if (Functions.Contains("Q"))
                    {
                        GridViewCommandColumnCustomButton QueryButton = new GridViewCommandColumnCustomButton();
                        QueryButton.Visibility = GridViewCustomButtonVisibility.BrowsableRow;
                        QueryButton.ID = "Query";
                        QueryButton.Text = "详细";

                        if (!String.IsNullOrEmpty(GlobalRunParms.QueryIcon))
                        {
                            QueryButton.Image.Url = GlobalRunParms.QueryIcon;
                            QueryButton.Image.ToolTip = "详细";
                        }
                        commandColumn.CustomButtons.Add(QueryButton);

                    }

                    commandColumn.UpdateButton.Visible = true;
                    commandColumn.UpdateButton.Text = "更新";

                    if (!String.IsNullOrEmpty(GlobalRunParms.UpdateIcon))
                    {
                        commandColumn.UpdateButton.Image.Url = GlobalRunParms.UpdateIcon;
                        commandColumn.UpdateButton.Image.ToolTip = "更新";
                    }

                    commandColumn.CancelButton.Visible = true;
                    commandColumn.CancelButton.Text = "取消";

                    if (!String.IsNullOrEmpty(GlobalRunParms.CancelIcon))
                    {
                        commandColumn.CancelButton.Image.Url = GlobalRunParms.CancelIcon;
                        commandColumn.CancelButton.Image.ToolTip = "取消";
                    }

                    //使用图片按钮
                    if ("Y".Equals(GlobalRunParms.IsImageButton))
                    {
                        commandColumn.ButtonType = ButtonType.Image;
                        TheGridView.Styles.CommandColumn.Spacing = Unit.Parse("5px"); ;
                    }

                    commandColumn.CellStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                    commandColumn.Caption = "操作";
                    TheGridView.Columns.Add(commandColumn);

                }
            }
        }


        public class GlobalComboxColumnEventArgs
        {
            /// <summary>
            /// 列对象
            /// </summary>
            public GridViewDataComboBoxColumn Column { get; set; }
        }
        /// <summary>
        /// 事件委托
        /// </summary>
        /// <param name="e"></param>
        public delegate void GlobalComboxColumnEventHandler(GlobalComboxColumnEventArgs e);
        /// <summary>
        /// 全局AddGridViewEvent中GridView的load事件中的下拉框事件对象
        /// </summary>
        public static event GlobalComboxColumnEventHandler OnGlobalComboxColumnLoad;

        /// <summary>
        /// 增加列修改的编辑器初始化事件并在load事件中加入设置下拉框的全局静态委托
        /// </summary>
        /// <param name="TheGridView"></param>
        public static void AddGridViewEvent(ASPxGridView TheGridView)
        {
            TheGridView.DataBound += new EventHandler((sender, e) =>
                {
                    ASPxGridView gridview = sender as ASPxGridView;

                    foreach (GridViewColumn item in TheGridView.Columns)
                    {
                        if (item is GridViewDataComboBoxColumn)
                        {
                            if (OnGlobalComboxColumnLoad != null)
                            {
                                OnGlobalComboxColumnLoad(new GlobalComboxColumnEventArgs() { Column = item as GridViewDataComboBoxColumn });
                            }
                        }
                    }
                }
                );

            TheGridView.CellEditorInitialize += new ASPxGridViewEditorEventHandler((sender, e) =>
            {
                if (e.Column.Name.Substring(0, 2) == "t_")//用于辨别列为数据列
                {
                    e.Editor.ClientInstanceName = "Edit_" + e.Column.FieldName;
                }

                if (TheGridView.SettingsText.PopupEditFormCaption == "详细")
                {
                    //当为查看时，所以列不可编辑(by SU)
                    e.Editor.ReadOnly = true;

                }
                else
                {
                    if (e.Column.FieldName == TheGridView.KeyFieldName)
                    {
                        if (e.Value != null && !string.IsNullOrEmpty(e.Value.ToString()))//当主键不为空时，主键不可修改！
                        {
                            e.Editor.ReadOnly = true;
                        }

                        //获得焦点(by SU)
                        e.Editor.Focus();
                    }
                }

                e.Column.EditFormCaptionStyle.Wrap = DevExpress.Utils.DefaultBoolean.False;
                //设置下拉框初始值为SelectIndex=0
                if (e.Editor is ASPxComboBox)
                {
                    (e.Editor as ASPxComboBox).ClientSideEvents.Init =
                        @"function(s,e){ if(s.GetSelectedIndex()==-1){s.SetSelectedIndex(0)}}";
                }
                //设置下拉式日期的初始值为当天
                if (e.Editor is ASPxDateEdit && e.Value == null)
                {
                    (e.Editor as ASPxDateEdit).Date = DateTime.Today;
                }
                //禁用所有下拉式控件的动态效果
                if (e.Editor is ASPxDropDownEdit)
                {
                    (e.Editor as ASPxDropDownEdit).EnableAnimation = false;
                }

                //设置所以编辑项回车变Tab事件(by SU)
                if (!String.IsNullOrEmpty(GlobalRunParms.EditorEnterEventName))
                {
                    e.Editor.SetClientSideEventHandler("KeyPress", "function(s,e){var key = event.keyCode;if( key==13){" + GlobalRunParms.EditorEnterEventName + "();}}");
                }
                //回车变Tab的默认实现
                //else
                //{
                //    e.Editor.SetClientSideEventHandler("KeyPress", "function(s,e){var key = event.keyCode;if( key==13){key=9;}}");
                //}
            });

            //查看按钮事件(by SU)
            TheGridView.CustomButtonCallback += new ASPxGridViewCustomButtonCallbackEventHandler((sender, e) =>
            {
                if (e.ButtonID == "Query")
                {
                    TheGridView.SettingsText.PopupEditFormCaption = "详细";
                    
                    TheGridView.StartEdit(e.VisibleIndex);
                }

            });
        }


        /// <summary>
        /// 操作日志记录函数
        /// </summary>
        /// <param name="User">操作人（用户编码）</param>
        /// <param name="UserType">操作人身份（用户类型）</param>
        /// <param name="Module">操作模块</param>
        /// <param name="ActionType">操作类型</param>
        /// <param name="ActionDescribe">操作说明描述</param>
        /// <returns>bool，是否以成功写入日志数据</returns>
        public static bool WriteLogData(string User, UserType sUserType, string Module, ActionType sActionType, string ActionDescribe)
        {
            using (uDataSet uds = new uDataSet("select * from sm_log where 1=2"))
            {
                uds.Tables[0].Columns["logid"].AutoIncrement = true;/*序号*/
                DataRow dr = uds.Tables[0].NewRow();
                dr["fsrq"] = DateTime.Now;
                dr["czr"] = User;
                switch (sUserType)
                {
                    case UserType.Customers:
                        dr["czrsf"] = "B";
                        break;
                    case UserType.InnerUsers:
                        dr["czrsf"] = "A";
                        break;
                    default:
                        dr["czrsf"] = "未知用户";
                        break;
                }

                dr["czmk"] = Module;
                switch (sActionType)
                {
                    case ActionType.Login:
                        dr["czfs"] = "登入";
                        break;
                    case ActionType.Logout:
                        dr["czfs"] = "登出";
                        break;
                    case ActionType.Delete:
                        dr["czfs"] = "删除";
                        break;
                    case ActionType.Update:
                        dr["czfs"] = "更新";
                        break;
                    case ActionType.Insert:
                        dr["czfs"] = "新增";
                        break;
                    case ActionType.Gen:
                        dr["czfs"] = "批量生成";
                        break;
                    default:
                        dr["czfs"] = "未知操作";
                        break;
                }

                dr["sm"] = ActionDescribe;
                uds.Tables[0].Rows.Add(dr);
                if (uds.Update() == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        /// <summary>
        /// 导出功能
        /// </summary>
        /// <param name="saveAs">是否直接打开或保存（true为保存，false为打开）</param>
        /// <param name="page">调用exporter的页面</param>
        /// <param name="agvExporter">exporter</param>
        /// <param name="sType">导出类型,application/ms-excel;text/enriched;application/pdf</param>
        /// <param name="sFileName">文件名</param>
        public static void GridViewExport(bool saveAs, Page page, ASPxGridViewExporter agvExporter, ExportType sType, string sFileName)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                //ASPxGridViewExporter1.OptionsPrint.PrintHeadersOnEveryPage = false;
                //ASPxGridViewExporter1.OptionsPrint.PrintFilterHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintColumnHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintRowHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintDataHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;

                string contentType = "", fileName = "";

                switch (sType)
                {
                    case ExportType.Excel:
                        contentType = "application/ms-excel";
                        fileName = sFileName + ".xls";
                        agvExporter.WriteXls(stream);
                        break;
                    case ExportType.Rtf:

                        contentType = "text/enriched";
                        fileName = sFileName + ".rtf";
                        agvExporter.WriteRtf(stream);
                        break;
                    case ExportType.Pdf:
                        contentType = "application/pdf";
                        fileName = sFileName + ".pdf";
                        agvExporter.WritePdf(stream);
                        break;
                    default:
                        break;
                }

                byte[] buffer = stream.GetBuffer();

                string disposition = saveAs ? "attachment" : "inline";
                page.Response.Clear();
                page.Response.Buffer = false;
                page.Response.AppendHeader("Content-Type", contentType);
                page.Response.AppendHeader("Content-Transfer-Encoding", "binary");
                page.Response.AppendHeader("Content-Disposition", disposition + "; filename=" + fileName);
                page.Response.BinaryWrite(buffer);
                page.Response.End();
            }
        }
        public static Type GetType(string p_TypeFullName)
        {
            Type _TypeInfo = Type.GetType(p_TypeFullName);
            if (_TypeInfo != null) return _TypeInfo;
            Assembly[] _Assembly = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i != _Assembly.Length; i++)
            {
                _TypeInfo = _Assembly[i].GetType(p_TypeFullName);
                if (_TypeInfo != null) return _TypeInfo;
            }
            return null;
        }
        #region 暂停使用的方法
        ///// <summary>
        ///// 序列化对象生成字节流，Soap形式
        ///// </summary>
        ///// <param name="obj">要序列化的可序列化对象</param>
        ///// <returns>byte[]，返回对象序列化且压缩过后的byte[]数据字节流</returns>
        //public static byte[] GetSoapSerializedObject(object obj)
        //{
        //    IFormatter formatter = new SoapFormatter();
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        formatter.Serialize(stream, obj);
        //        byte[] bytes = stream.ToArray();
        //        int lenbyte = bytes.Length;
        //        using (MemoryStream desstream = new MemoryStream())
        //        {
        //            using (GZipStream compStream = new GZipStream(desstream, CompressionMode.Compress, true))
        //            {
        //                compStream.Write(bytes, 0, lenbyte);
        //                compStream.Close();
        //                desstream.Close();
        //                stream.Close();
        //                return desstream.ToArray();
        //            }
        //        }
        //    }

        //}
        ///// <summary>
        ///// 反序列化对象，Soap形式
        ///// </summary>
        ///// <param name="bytes">源数据字节流</param>
        ///// <returns>object，由数据字节流序列化而来的对象，需进行转换</returns>
        //public static object GetSoapDeserializedObject(byte[] bytes)
        //{
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        stream.Write(bytes, 0, bytes.Length);
        //        stream.Position = 0;
        //        using (System.IO.Compression.GZipStream Gstraem = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress, true))
        //        {
        //            using (MemoryStream output = new MemoryStream())
        //            {
        //                byte[] buff = new byte[4096];
        //                int read = -1;
        //                read = Gstraem.Read(buff, 0, buff.Length);
        //                while (read > 0)
        //                {
        //                    output.Write(buff, 0, read);
        //                    read = Gstraem.Read(buff, 0, buff.Length);
        //                }
        //                Gstraem.Close();
        //                byte[] rebytes = output.ToArray();
        //                output.Close();
        //                stream.Close();
        //                using (MemoryStream ms = new MemoryStream(rebytes))
        //                {
        //                    IFormatter formatter = new SoapFormatter();
        //                    return formatter.Deserialize(ms);
        //                }
        //            }
        //        }
        //    }
        //}
        ///// <summary>
        ///// 序列化对象生成字节流，XML形式
        ///// </summary>
        ///// <param name="obj">要序列化的可序列化对象</param>
        ///// <returns>byte[]，返回对象序列化且压缩过后的byte[]数据字节流</returns>
        //public static byte[] GetXMLSerializedObject(object obj)
        //{
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        //        ser.Serialize(stream, obj);
        //        byte[] bytes = stream.ToArray();
        //        int lenbyte = bytes.Length;
        //        MemoryStream desstream = new MemoryStream();
        //        GZipStream compStream = new GZipStream(desstream, CompressionMode.Compress, true);
        //        compStream.Write(bytes, 0, lenbyte);
        //        compStream.Close();
        //        desstream.Close();
        //        stream.Close();
        //        return desstream.ToArray();
        //    }
        //}
        ///// <summary>
        ///// 反序列化对象，XML形式
        ///// </summary>
        ///// <param name="buffer">源数据字节流</param>
        ///// <param name="type">可序列化类型</param>
        ///// <returns>object，由数据字节流序列化而来的对象，需进行转换</returns>
        //public static object GetXMLDeserializedObject(byte[] buffer,Type type)
        //{
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        stream.Write(buffer, 0, buffer.Length);
        //        stream.Position = 0;
        //        System.IO.Compression.GZipStream Gstraem = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress, true);
        //        MemoryStream output = new MemoryStream();
        //        byte[] buff = new byte[4096];
        //        int read = -1;
        //        read = Gstraem.Read(buff, 0, buff.Length);
        //        while (read > 0)
        //        {
        //            output.Write(buff, 0, read);
        //            read = Gstraem.Read(buff, 0, buff.Length);
        //        }
        //        Gstraem.Close();
        //        byte[] rebytes = output.ToArray();
        //        output.Close();
        //        stream.Close();
        //        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(rebytes))
        //        {
        //            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type);
        //            return ser.Deserialize(ms);
        //        }
        //    }
        //}

        ///// <summary>
        ///// 压缩字符串并转化到字节流
        ///// </summary>
        ///// <param name="str">需要压缩的字符串</param>
        ///// <returns>返回字节流</returns>
        //public static byte[] CommPressbyGZip(string str)
        //{
        //    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
        //    int lenbyte = bytes.Length;
        //    using (MemoryStream desstream = new MemoryStream())
        //    {
        //        GZipStream compStream = new GZipStream(desstream, CompressionMode.Compress, true);
        //        compStream.Write(bytes, 0, lenbyte);
        //        compStream.Close();
        //        desstream.Close();
        //        return desstream.ToArray();
        //    }
        //}

        ///// <summary>
        ///// 解压缩字节流转化到字符串
        ///// </summary>
        ///// <param name="bytes">需要压缩的字节流</param>
        ///// <returns>返回解压后的字符串</returns>
        //public static string DecompressbyGZip(byte[] bytes)
        //{
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        stream.Write(bytes, 0, bytes.Length);
        //        stream.Position = 0;
        //        using (System.IO.Compression.GZipStream Gstraem = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress, true))
        //        {
        //            using (MemoryStream output = new MemoryStream())
        //            {
        //                byte[] buff = new byte[4096];
        //                int read = -1;
        //                read = Gstraem.Read(buff, 0, buff.Length);
        //                while (read > 0)
        //                {
        //                    output.Write(buff, 0, read);
        //                    read = Gstraem.Read(buff, 0, buff.Length);
        //                }
        //                Gstraem.Close();
        //                byte[] rebytes = output.ToArray();
        //                output.Close();
        //                stream.Close();
        //                return System.Text.Encoding.UTF8.GetString(rebytes);
        //            }
        //        }
        //    }
        //}
        #endregion

        [DllImport("encipher.dll", EntryPoint = "encipher")]
        public extern static int encipher(StringBuilder str);
    }
}
